package com.glodon.paas.framework.registry.client.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.regex.Pattern;

import static com.google.common.base.Strings.isNullOrEmpty;

/**
 * @author Don Li
 */
public class EnvironmentUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(EnvironmentUtils.class);

    private static final String IPV4_ADDRESS_REGEX =
            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    private static final Pattern IPV4_PATTERN = Pattern.compile(IPV4_ADDRESS_REGEX);

    public static String getInstanceName() {
        return "client";
//        throw new UnsupportedOperationException();
    }

    public static String getIp(String interfaceName) {
        if (isNullOrEmpty(interfaceName)) {
            return null;
        }
        try {
            for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                String name = networkInterface.getName();
                if (name.equalsIgnoreCase(interfaceName)) {
                    for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                        if (IPV4_PATTERN.matcher(inetAddress.getCanonicalHostName()).matches()) {
                            return inetAddress.getCanonicalHostName();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            LOGGER.error("Error getting ip address for interface " + interfaceName, e);
        }
        return null;
    }
}
